import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:github_client_flutter/common/funs.dart';
import 'package:github_client_flutter/index.dart';

class LoginRoute extends StatefulWidget {
  const LoginRoute({super.key});

  @override
  State<LoginRoute> createState() => _LoginRouteState();
}

class _LoginRouteState extends State<LoginRoute> {
  TextEditingController unameController =
      TextEditingController(text: 'wenfp@palmtrends.com');
  TextEditingController upasswordController = TextEditingController(text: 'skdiena123');

  bool showPassword = false;
  GlobalKey formKey = GlobalKey<FormState>();
  bool nameAutoFocus = true;

  @override
  Widget build(BuildContext context) {
    var gm = GmLocalizations.of(context);
    return Scaffold(
      appBar: AppBar(title: Text(gm.login)),
      body: Padding(
        padding: const EdgeInsets.all(26.0),
        child: Form(
          key: formKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(
            children: [
              TextFormField(
                autofocus: nameAutoFocus,
                controller: unameController,
                decoration: InputDecoration(
                  labelText: gm.userName,
                  hintText: gm.userName,
                  prefixIcon: const Icon(Icons.person),
                ),
              ),
              TextFormField(
                autofocus: !nameAutoFocus,
                controller: upasswordController,
                decoration: InputDecoration(
                  labelText: gm.password,
                  hintText: gm.password,
                  prefixIcon: const Icon(Icons.lock),
                  suffixIcon: IconButton(
                    icon: Icon(showPassword ? Icons.visibility_off : Icons.visibility),
                    onPressed: () {
                      setState(() {
                        showPassword = !showPassword;
                      });
                    },
                  ),
                ),
                obscureText: !showPassword,
                validator: (v) {
                  return v == null || v.trim().isNotEmpty ? null : gm.passwordRequired;
                },
              ),
              Padding(
                padding: const EdgeInsets.only(top: 20),
                child: ConstrainedBox(
                  constraints: const BoxConstraints.expand(height: 55.0),
                  child: ElevatedButton(
                    child: Text(gm.login),
                    onPressed: () {
                      _onLogin();
                    },
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void _onLogin() async {
    if ((formKey.currentState as FormState).validate()) {
      showLoading(context);
      var gm = GmLocalizations.of(context);
      User? user;
      try {
        user = await Git(context).login(unameController.text, upasswordController.text);
        print("login -> $user");
        Provider.of<UserModel>(context, listen: false).user = user;
      } on DioException catch (e) {
        if (e.response?.statusCode == 401) {
          showToast(gm.userNameOrPasswordWrong);
        } else {
          showToast(e.toString());
        }
      } finally {
        Navigator.of(context).pop();
      }
      if (user != null) {
        Navigator.of(context).pop();
      }
    }
  }
}
